<template>
  <el-dialog :title="'批量编辑签到记录'" :visible.sync="visible" width="700px" :close-on-click-modal="false" append-to-body>
    <div class="batch-edit-content">
      <!-- 选中记录列表 -->
      <div class="selected-records">
        <h4>已选择 {{ selectedRecords.length }} 条记录：</h4>
        <div class="records-list">
          <el-tag
            v-for="record in selectedRecords"
            :key="record.id"
            type="info"
            size="small"
            style="margin: 2px;"
          >
            {{ record.teacherName }} - {{ record.signDate }} {{ getPeriodText(record.period) }}
          </el-tag>
        </div>
      </div>

      <!-- 编辑表单 -->
      <el-form ref="dataForm" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="签到状态" prop="status">
              <el-select v-model="dataForm.status" placeholder="请选择状态" :style="{ width: '100%' }">
                <el-option label="正常签到" value="Normal" />
                <el-option label="迟到" value="Late" />
                <el-option label="请假" value="Leave" />
                <el-option label="早退" value="EarlyLeave" />
                <el-option label="缺勤" value="Absent" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签到方式">
              <el-select v-model="dataForm.method" placeholder="请选择方式（可选）" :style="{ width: '100%' }">
                <el-option label="不修改" value="" />
                <el-option label="手动签到" value="MANUAL" />
                <el-option label="扫码签到" value="QR_CODE" />
                <el-option label="人脸识别" value="FACE_RECOGNITION" />
                <el-option label="指纹识别" value="FINGERPRINT" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="签到时间">
              <el-date-picker
                v-model="dataForm.signTime"
                type="datetime"
                placeholder="请选择签到时间（可选）"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :style="{ width: '100%' }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="dataForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作提示 -->
      <el-alert
        title="批量编辑说明"
        type="info"
        :closable="false"
        show-icon
      >
        <div slot="description">
          <p>• 签到状态为必填项，将应用到所有选中的记录</p>
          <p>• 签到方式、签到时间和备注为可选项，留空则不修改原有值</p>
          <p>• 批量操作不可撤销，请谨慎操作</p>
        </div>
      </el-alert>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确认批量修改</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { batchUpdateSignRecord } from '@/api/campus/trainSignRecord'

export default {
  data() {
    return {
      visible: false,
      btnLoading: false,
      selectedRecords: [],
      dataForm: {
        status: '',
        method: '',
        signTime: '',
        remark: ''
      },
      dataRule: {
        status: [{ required: true, message: '签到状态不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    init(records) {
      this.selectedRecords = records
      this.dataForm = {
        status: '',
        method: '',
        signTime: '',
        remark: ''
      }
      this.visible = true
    },
    getPeriodText(period) {
      const periodMap = {
        'AM': '上午',
        'PM': '下午',
        'EVE': '晚上'
      }
      return periodMap[period] || period
    },
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$confirm(`确认要批量修改这 ${this.selectedRecords.length} 条签到记录吗？`, '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.btnLoading = true
            const params = {
              ids: this.selectedRecords.map(record => record.id),
              status: this.dataForm.status,
              method: this.dataForm.method || undefined,
              signTime: this.dataForm.signTime || undefined,
              remark: this.dataForm.remark || undefined
            }
            batchUpdateSignRecord(params).then((response) => {
              const result = response.data || response
              if (result.successCount > 0) {
                this.$message.success(`批量修改完成：成功 ${result.successCount} 条，失败 ${result.failCount || 0} 条`)
              }
              if (result.failedList && result.failedList.length > 0) {
                this.$message.warning(`部分记录修改失败：${result.failedList.join(', ')}`)
              }
              this.visible = false
              this.$emit('refresh')
            }).catch(() => {
              this.btnLoading = false
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.batch-edit-content {
  max-height: 500px;
  overflow-y: auto;
}

.selected-records {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-records h4 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.records-list {
  max-height: 120px;
  overflow-y: auto;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-alert {
  margin-top: 15px;
}
</style>